package com.sgb.kjwl.view.ui.activity.self.packers;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLaborServiceAndEmploymentPublishBinding;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.packers.LabourServiceAndEmploymentEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.PointUtils;
import com.sgb.kjwl.utils.UploadCheckHelper;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.widget.SalaryPopWindow;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.packers.LaborServiceAndEmploymentPublishViewModel;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author younghow
 * @date 2021/7/5
 * description:劳务用工发布页面
 */
public class LaborServiceAndEmploymentPublishActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    ActivityLaborServiceAndEmploymentPublishBinding mBinding;
    LaborServiceAndEmploymentPublishViewModel mViewModel;
    private int isEnable = 1, mSalaryType = 0, mSalaryUnit = 0;
    private String mNo = "", mProvinceNo = "", mProvinceName = "", mCityNo = "", mCityName = "", mAreaNo = "", mAreaName = "", mServicePersonId = "", mServicePersonName = "", mIndustryNo = "", mCategoryNo = "", mWorkNo = "";
    private CityPickView mCityPickView, mWorkTypeView;
    private int cityPosition1, cityPosition2, cityPosition3, mWorkCityPosition1, mWorkCityPosition2, mWorkCityPosition3, mServicePersonPos, mPayPos, mApplyPos;
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private final List<List<AddressEntity<List<AddressEntity>>>> mWorkOpt2 = new ArrayList<>();
    private final List<List<List<AddressEntity>>> mWorkOpt3 = new ArrayList<>();
    private boolean mIsSuccess = false, isVisible = false;
    /**
     * 选择客服的底部dialog
     */
    private OptionsPickerView mOptions;
    /**
     * 自定义薪资的输入框的底部弹出框
     */
    private SalaryPopWindow salaryPopWindow;
    private String price = "";
    private LabourServiceAndEmploymentEntity mEntity;
    private String mLongitude,mLatitude,mAddress;

    @Override
    protected void initView() {
        super.initView();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_labor_service_and_employment_publish);

        mBinding.setLifecycleOwner(this);
        mViewModel = new ViewModelProvider(this).get(LaborServiceAndEmploymentPublishViewModel.class);
        mBinding.iitIsApply.setContent("启用");

        mBinding.iitPersonNumber.setInfilterType(ItemInputTextView.TYPE_NUM);

        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 2){
            mBinding.iitSelectCustomService.setVisibility(View.GONE);
        }

        mBinding.iitPersonNumber.setMaxLength(3,"最多可输入3位");
        mBinding.iitLinkman.setMaxLength(10,"最多可输入10个字");
        mBinding.iitPhone.setMaxLength(11,"最多可输入11个字");
        mBinding.etWorkContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mBinding.tvSize.setText(String.format(Locale.CHINA,"%d/%d",mBinding.etWorkContent.getText().toString().length(),300));
            }
        });

        initPopWindow();
        initButton();
        initData();
        initLiveData();
        initEntity();
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mEntity != null) {
            mActionBar.setTitle("编辑劳务信息");
        }
    }

    private void initEntity() {
        mEntity = (LabourServiceAndEmploymentEntity) getIntent().getSerializableExtra("entity");
        if (mEntity != null) {
            mSalaryType = Integer.parseInt(mEntity.getSalaryType());
            mNo = mEntity.getNo();
            mProvinceNo = mEntity.getProvinceNo();
            mCityNo = mEntity.getCityNo();
            mAreaNo = mEntity.getAreaNo();
            mServicePersonId = mEntity.getImId();
            mServicePersonName = mEntity.getImName();
            mIndustryNo = mEntity.getIndustryNo();
            mCategoryNo = mEntity.getCategoryNo();
            mWorkNo = mEntity.getWorkNo();
            isEnable = mEntity.getIsEnable();
            mSalaryUnit = mEntity.getSalaryUnit();
            price = String.valueOf(mEntity.getSalary());

            mBinding.tvType.setText(String.format("%s/%s/%s",mEntity.getIndustryName(),mEntity.getCategoryName(),mEntity.getWorkName()));
            mBinding.iitSelectPay.setContent(mSalaryType == 1 ? "自定义薪资" : (mSalaryType == 2 ? "电议" : "面议"));
            mBinding.etSalary.setVisibility(mSalaryType == 1 ? View.VISIBLE : View.GONE);
            if (mSalaryType == 1){
                mBinding.etSalary.setContent(PointUtils.originalPrice(Double.parseDouble(price)) + "元/" + (mEntity.getSalaryUnit() == 1 ? "月" : mEntity.getSalaryUnit() == 2 ? "季度" : "年"));
            }
            mBinding.iitPersonNumber.setContent(String.valueOf(mEntity.getEmploymentNumber()));
            mBinding.iitWorkAddress.setContent(mEntity.getProvinceName() + mEntity.getCityName() + mEntity.getAreaName()+(TextUtils.isEmpty(mEntity.getAddress()) ? "" : mEntity.getAddress()),13);
            mBinding.iitLinkman.setContent(mEntity.getContactName());
            mBinding.iitPhone.setContent(mEntity.getContactNumber());
            mBinding.iitIsApply.setContent(mEntity.getIsEnable() == 0 ? "禁用" : "启用");
            mBinding.iitSelectCustomService.setContent(mEntity.getImName());
            mBinding.etWorkContent.setText(mEntity.getWorkContent());
            mBinding.btnRelease.setText("确定");
        }
    }

    private void initLiveData() {
        mViewModel.loadingLiveData.observe(this, aBoolean -> DialogHelper.showProgressDialog(LaborServiceAndEmploymentPublishActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));
        mViewModel.successLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());
        mViewModel.errorLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());

        mViewModel.mCityData.observe(this, addressEntities -> {
            for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> addressEntity : addressEntities) {
                opt2.add(addressEntity.getChildren());
                List<List<AddressEntity>> list = new ArrayList<>();
                for (AddressEntity<List<AddressEntity>> child : addressEntity.getChildren()) {
                    list.add(child.getChildren());
                }
                opt3.add(list);
            }
            mCityPickView = new CityPickBuilder(LaborServiceAndEmploymentPublishActivity.this, (options1, options2, options3, v) -> {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                }
                String content = addressEntities.get(options1).getName()
                        + opt2.get(options1).get(options2).getName()
                        + areaName;
                mBinding.iitWorkAddress.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
                mProvinceNo = addressEntities.get(options1).getNo();
                mCityNo = opt2.get(options1).get(options2).getNo();
                mAreaNo = opt3.get(options1).get(options2).get(options3).getNo();
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            mCityPickView.setPicker(addressEntities, opt2, opt3);
            mCityPickView.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
            mCityPickView.setTitleText("请选择地址");
        });

        mViewModel.mUploadSuccessData.observe(this, aBoolean -> {
            if (aBoolean) {
                mIsSuccess = true;
            }
            onBackPressed();
        });

        mViewModel.mWorkTypeData.observe(this, pickFilterEntities -> {
            for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> addressEntity : pickFilterEntities) {
                List<AddressEntity<List<AddressEntity>>> secondLevel = addressEntity.getChildren();
                if (secondLevel.size() <= 0){
                    List<AddressEntity> addressEntities1 = new ArrayList<>();
                    addressEntities1.add(new AddressEntity("","",""));
                    secondLevel.add(new AddressEntity<>("", "", addressEntities1));
                }
                mWorkOpt2.add(secondLevel);
                List<List<AddressEntity>> list = new ArrayList<>();
                for (AddressEntity<List<AddressEntity>> child : addressEntity.getChildren()) {
                    List<AddressEntity> third = child.getChildren();
                    if (third.size() <= 0){
                        third.add(new AddressEntity("","",""));
                    }
                    list.add(third);
                }
                mWorkOpt3.add(list);
            }
            mWorkTypeView = new CityPickBuilder(LaborServiceAndEmploymentPublishActivity.this, (options1, options2, options3, v) -> {
                String areaName;
                try {
                    if (mWorkOpt3.get(options1).get(options2).get(options3) == null) {
                        areaName = "";
                    } else {
                        areaName = mWorkOpt3.get(options1).get(options2).get(options3).getName();
                        mWorkCityPosition3 = options3;
                    }
                } catch (IndexOutOfBoundsException e) {
                    areaName = "";
                }
                String content = pickFilterEntities.get(options1).getName() + "/"
                        + mWorkOpt2.get(options1).get(options2).getName() + (!"".equals(areaName) ? "/" : "")
                        + areaName;
                mBinding.tvType.setText(content);
                mWorkCityPosition1 = options1;
                mWorkCityPosition2 = options2;
                mIndustryNo = pickFilterEntities.get(options1).getNo();
                mCategoryNo = mWorkOpt2.get(options1).get(options2).getNo();
                try {
                    mWorkNo = mWorkOpt3.get(options1).get(options2).get(options3).getNo();
                } catch (IndexOutOfBoundsException e) {
                    mWorkNo = "";
                }
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            mWorkTypeView.setPicker(pickFilterEntities, mWorkOpt2, mWorkOpt3);
            mWorkTypeView.setSelectOptions(mWorkCityPosition1, mWorkCityPosition2, mWorkCityPosition3);
            mWorkTypeView.setTitleText("请选择工种");
        });

        mViewModel.mPickSelectData.observe(this, pickSelectEntities -> {
            if (mOptions == null) {
                mOptions = new OptionsPickerBuilder(LaborServiceAndEmploymentPublishActivity.this, (options1, options2, options3, v) -> {
                    mServicePersonPos = options1;
                    mServicePersonName = pickSelectEntities.get(options1).getProjectscale();
                    mServicePersonId = pickSelectEntities.get(options1).getNo();
                    mBinding.iitSelectCustomService.setContent(mServicePersonName);
                }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            }
            mOptions.setTitleText("选择咨询客服");
            mOptions.setPicker(pickSelectEntities);
            mOptions.setSelectOptions(mServicePersonPos);
            mOptions.show();

        });
    }

    public void showSalaryFsPop(List<PickSelectEntity> list) {
        OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(LaborServiceAndEmploymentPublishActivity.this, (options1, options2, options3, v) -> {
            mBinding.iitSelectPay.setContent(list.get(options1).getProjectscale());
            mSalaryType = Integer.parseInt(list.get(options1).getNo());
            isVisible = "自定义薪资".equals(list.get(options1).getProjectscale());
            mBinding.etSalary.setVisibility(isVisible ? View.VISIBLE : View.GONE);
            mPayPos = options1;
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        projectCategoryOption.setPicker(list);
        projectCategoryOption.setSelectOptions(mPayPos);
        projectCategoryOption.setTitleText("选择薪资方式");
        projectCategoryOption.show();
    }

    public void showApply(List<PickSelectEntity> list) {
        OptionsPickerView mApplyOption = new OptionsPickerBuilder(LaborServiceAndEmploymentPublishActivity.this, (options1, options2, options3, v) -> {
            mBinding.iitIsApply.setContent(list.get(options1).getProjectscale());
            isEnable = Integer.parseInt(list.get(options1).getNo());
            mApplyPos = options1;
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        mApplyOption.setPicker(list);
        mApplyOption.setSelectOptions(mApplyPos);
        mApplyOption.setTitleText("请选择是否启用");
        mApplyOption.show();
    }

    private void initData() {
        int companyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (companyType == 0) {
            mServicePersonName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
            mServicePersonId = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
            mBinding.iitSelectCustomService.setContent(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, ""));
            mBinding.iitSelectCustomService.setVisibility(View.GONE);
        }

        mViewModel.getLinkAgeWorkType();
        mViewModel.getCityList();
    }


    @SuppressLint("WrongConstant")
    private void initPopWindow() {
        salaryPopWindow = new SalaryPopWindow(LaborServiceAndEmploymentPublishActivity.this,6);
        salaryPopWindow.setBgView(mBinding.grayLayout);
        salaryPopWindow.setOnResultClick((price1, unit, no) -> {
            price = price1 + "";
            mBinding.etSalary.setContent(!TextUtils.isEmpty((String) price1) ? price + "元/" + unit : "");
            mSalaryUnit = Integer.parseInt((String) no);
        });

        salaryPopWindow.setPopDataChange("月","季度","年");
        salaryPopWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        salaryPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    private void initButton() {
        mBinding.iitSelectType.setOnClickListener(this);
        mBinding.iitSelectPay.setOnWholeItemClickListener(this);
        mBinding.etSalary.setOnWholeItemClickListener(this);
        mBinding.iitWorkAddress.setOnWholeItemClickListener(this);
        mBinding.iitIsApply.setOnWholeItemClickListener(this);
        mBinding.iitSelectCustomService.setOnWholeItemClickListener(this);
        mBinding.btnRelease.setOnClickListener(this);
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        int id = v.getId();
        if (id == R.id.btn_release) {
            if (TextUtils.isEmpty(mBinding.tvType.getText().toString())) {
                MToast.showToast(this, mBinding.tvType.getHint().toString());
                return;
            }

            if (!UploadCheckHelper.textCheckForCrew(this, new ItemInputTextView[]{mBinding.iitSelectPay, mBinding.etSalary, mBinding.iitPersonNumber
                    , mBinding.iitWorkAddress, mBinding.iitLinkman, mBinding.iitPhone, mBinding.iitIsApply}, isVisible)) {
                return;
            }

            if ("0".equals(mBinding.iitPersonNumber.getContent())) {
                MToast.showToast(this, "用工人数不能为0");
                return;
            }

            if (mBinding.iitLinkman.getContent().length() < 2) {
                MToast.showToast(this, "联系人最少输入两位数");
                return;
            }

            if (!CheckUtils.checkMobile(mBinding.iitPhone.getContent())) {
                MToast.showToast(this, "请输入正确的电话号码");
                return;
            }

            upload();
        } else if (id == R.id.iit_select_type) {
            mWorkTypeView.show();
        }
    }

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        if (!"".equals(mNo)) {
            map.put("no", mNo);
        }

        map.put("salaryType", mSalaryType);
        if (mSalaryType == 1) {
            map.put("salaryUnit", mSalaryUnit);
            map.put("salary", price);
        }
        map.put("employmentNumber", mBinding.iitPersonNumber.getContent());
        map.put("workContent", mBinding.etWorkContent.getText().toString());
        map.put("contactName", mBinding.iitLinkman.getContent());
        map.put("contactNumber", mBinding.iitPhone.getContent());
        map.put("provinceNo", mProvinceNo);
        map.put("provinceName", mProvinceName);
        map.put("cityNo", mCityNo);
        map.put("cityName", mCityName);
        map.put("areaNo", mAreaNo);
        map.put("areaName", mAreaName);
        map.put("imid", mServicePersonId);
        map.put("imName", mServicePersonName);
        map.put("industryNo", mIndustryNo);
        map.put("categoryNo", mCategoryNo);
        map.put("workNo", mWorkNo);
        map.put("isEnable", isEnable);
        map.put("latitude", mLatitude);
        map.put("longitude", mLongitude);
        map.put("address", mAddress);
        int companyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (companyType == 0) {
            map.put("userNo", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
        } else if (companyType == 1) {
            map.put("companyNo", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        }  else if (companyType == 2){
            map.put("teamNo", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, ""));
        }
        mViewModel.upload(map);
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.iit_select_pay) {
            showSalaryFsPop(mViewModel.getSalaryFs());
        } else if (id == R.id.iit_work_address) {
            AMapDialog.launch(this);
        } else if (id == R.id.iit_is_apply) {
            showApply(mViewModel.getApplyFs());
        } else if (id == R.id.iit_select_custom_service) {
            if (mOptions == null) {
                mViewModel.getCustomerData();
            } else {
                mOptions.show();
            }
        } else if (id == R.id.et_salary) {
            salaryPopWindow.showDownPopwindow(mBinding.grayLayout, true);
        }
    }

    @Override
    public void onBackPressed() {
        if (mIsSuccess) {
            setResult(1);
        }
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RequestCode.CODE_MAP) {
            AMapAddressEntity entity = AMapDialog.get(data);
            getAddress(entity);
        }
    }

    private void getAddress(AMapAddressEntity entity) {
        if (entity!=null){
            if ("北京".equals(entity.getProvince())&& "天津".equals(entity.getProvince())&& "上海".equals(entity.getProvince())&& "重庆".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"市");
                mProvinceName = entity.getProvince();
            }else if ("内蒙古".equals(entity.getProvince())&& "西藏".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"自治区");
                mProvinceName = entity.getProvince();
            } else if ("广西".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"壮族自治区");
                mProvinceName = entity.getProvince();
            }else if ("宁夏".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"回族自治区");
                mProvinceName = entity.getProvince();
            }else if ("新疆".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"维吾尔族自治区");
                mProvinceName = entity.getProvince();
            }else if ("香港".equals(entity.getProvince())&& "澳门".equals(entity.getProvince())){
                entity.setProvince(entity.getProvince()+"特别行政区");
                mProvinceName = entity.getProvince();
            }else{
                entity.setProvince(entity.getProvince()+"省");
                mProvinceName = entity.getProvince();
            }
            mProvinceNo = entity.getProvinceNo();
            mCityNo = entity.getCityNo() ;
            mCityName = entity.getCity() + "市";
            mAreaNo = entity.getDistrictNo();
            mAreaName = entity.getDistrict() + "区";
            mLongitude = String.valueOf(entity.getLongitude());
            mLatitude = String.valueOf(entity.getLatitude());
            mAddress = String.format("%s",entity.getSnippet());
            mBinding.iitWorkAddress.setContent(String.format("%s%s%s%s",mProvinceName,mCityName,mAreaName,entity.getSnippet()),13);
        }
    }
}
